package vn.cent.game.cardtype.server;

import java.util.List;

import vn.cent.game.cardtype.main.CardTypeGameExtension;
import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;

public class UserDisconnect extends BaseServerEventHandler {

	@Override
	public void handleServerEvent(ISFSEvent evt) throws SFSException {
		// TODO Auto-generated method stub
		User user = (User) evt.getParameter(SFSEventParam.USER);
		
		// Get room that user left
		Room room = null;
		@SuppressWarnings("unchecked")
		List<Room> joinedRooms = (List<Room>) evt
				.getParameter(SFSEventParam.JOINED_ROOMS);
		if(joinedRooms.size() > 0){
			room = joinedRooms.get(0);
		}
		
		if(room != null && room.isGame()){
			CardTypeGameExtension gameExt = (CardTypeGameExtension) getParentExtension();
			
			User remainUser = FindRemainPlayer(room.getPlayersList(), user);
			if(remainUser == null)
				return;
			gameExt.send("withdraw", null, remainUser);
		}
	}
	
	private User FindRemainPlayer(List<User> players, User leftUser){
		for (User user : players) {
			if(user.getId() != leftUser.getId()){
				return user;
			}
		}
		return null;
	}
}
